package cn.xiaye.httpserver.util;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import cn.xiaye.httpserver.Constant;

public class MarkerUtil {
	public static Pattern pv = Pattern.compile("\\$\\{(\\w*)\\}");

	/***
	 * 格式化输出文本内容
	 * 
	 * @param templateFile
	 * @param map
	 * @return
	 */
	public static String processFile(String templateFile, HashMap<String, Object> map) {
		InputStream is = null;
		byte[] by = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			is = new FileInputStream(Constant.TEMPLATE_PATH + File.separator + templateFile);
			int b = -1;
			while ((b = is.read()) != -1) {
				bos.write(b);
			}

			by = bos.toByteArray();
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			try {
				is.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}

		String fileText = new String(by);
		Matcher mch = pv.matcher(fileText);
		while (mch.find()) {
			String toRel = mch.group();
			String key = mch.group(1);
			Object value = map.get(key);
			fileText = fileText.replace(toRel, value == null ? "null" : value.toString());
		}
		return fileText;
	}
}
